﻿using glTech.CommonLib.Data;
using RESTFinder.Service.Utils;
using System.Data;
using System.Data.Common;
using System.IO;

namespace RESTFinder.Service.Repositories
{
    public abstract class CoreRepository<TEntity> : IRepository<TEntity>
    {
        protected static IDatabase _database;
        private static object Lock = new object();

        static CoreRepository()
        {
            var dbPath = PathUtil.GetDatabasePath();
            var dbDirectory = Path.GetDirectoryName(dbPath);
            if (dbDirectory != null && !Directory.Exists(dbDirectory))
            {
                Directory.CreateDirectory(dbDirectory);
            }
            string connectionString = string.Format("Data Source={0};Version=3;Password=gl;", dbPath);
            _database = new SqliteDatabase(connectionString);

            CreateDatabase();
        }

        private static void CreateDatabase()
        {
            string sql = "CREATE TABLE IF NOT EXISTS AppSetting(Key nvarchar(50),Value nvarchar(50) , PRIMARY KEY  (Key));"+
                "CREATE TABLE IF NOT EXISTS Document(Md5 varchar(20),FileName nvarchar(100),FullPath nvarchar(200),Extension varchar(10),ContentType varchar(10),RDate DateTime,LDate DateTime ,PRIMARY KEY(Md5))";
            Execute(sql);
        }



        public static void Execute(string sql, params DbParameter[] parameters)
        {
            lock (Lock)
            {
                _database.Execute(sql, CommandType.Text, parameters, true, command => command.ExecuteNonQuery());
            }
        }

        public object ExecuteScalarText(string sql, params DbParameter[] parameters)
        {
            lock (Lock)
            {
                return _database.ExecuteScalarText(sql, parameters);
            }
        }

        public TResult ExecuteReaderText<TResult>(string sql, System.Func<System.Data.IDataReader, TResult> func, params DbParameter[] parameters)
        {
            lock (Lock)
            {
                return _database.ExecuteReaderText<TResult>(sql, func, parameters);
            }
        }
    }
}
